import './LinkProduct.less'
import { Input, Button, App, Popconfirm, Typography, Card, Form } from 'antd'
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons'
import FormUploadOneImg from '@/components/FormUploadOneImg'
import LinkFormat from '../LinkFormat/LinkFormat'
import React, { forwardRef, useImperativeHandle, useState, useEffect } from 'react'
import { useModel } from '@umijs/max'

const typeObj = {
  bannerArr: {
    text: '图片广告',
    data: 'bannerArr',
    aspect: 4 / 1
  },
  navigationArr: {
    text: '图文导航',
    data: 'navigationArr'
    // aspect: 1 / 1
  }
}

function LinkProduct({ type }, ref) {
  const [currentCount, setCurrentCount] = useState([])
  const { message } = App.useApp()
  const [basisForm] = Form.useForm()
  const { setShopUpdateData, shopData } = useModel('ShopDecoration')

  useEffect(() => {
    // 设置表单默认值
    basisForm.setFieldsValue({
      [type]: shopData[typeObj[type].data] || {}
    })
    setCurrentCount(shopData[typeObj[type].data] || [])
  }, [shopData])

  // 新增
  const handleAddProduct = addFn => {
    if (currentCount.length >= 10) {
      message.error('最多添加10个')
      return
    }

    setCurrentCount(prev => {
      return [...prev, {}]
    })

    addFn({
      img_url: '',
      linkArr: []
    })
  }

  // 删除
  const handleRemoveProduct = (removeFn, field) => {
    setCurrentCount(prev => {
      prev.splice(0, 1)
      return [...prev]
    })

    removeFn(field.name)
  }

  // 处理表单提交
  const handleFinish = async () => {
    await basisForm.validateFields()
    const values = basisForm.getFieldsValue()

    values[type].forEach((item, index) => {
      item.linkArr.forEach(link => {
        item.display_category_list = link.display_category_list
        item.current_click = index + 1
      })
    })

    return values
  }

  // 暴露给父组件的方法
  useImperativeHandle(ref, () => ({
    handleFinish
  }))

  // 监听 form 表单值变化
  const onValuesChange = (changedValues, allValues) => {
    // console.log('changedValues', changedValues)
    // console.log('allValues', allValues)
    setShopUpdateData(allValues)
  }

  return (
    <div className='link_product'>
      <Form form={basisForm} name='form' onValuesChange={onValuesChange}>
        <Form.List name={type}>
          {(fields, { add, remove }) => (
            <div
              style={{
                display: 'flex',
                rowGap: 16,
                flexDirection: 'column'
              }}
            >
              {fields.map(field => (
                <Card
                  bordered={false}
                  bodyStyle={{ background: '#F7F8FA' }}
                  headStyle={{ background: '#F7F8FA' }}
                  size='small'
                  title={`${typeObj[type].text} ${field.name + 1}`}
                  key={field.key}
                  extra={
                    <Popconfirm
                      title='确认删除吗?'
                      onConfirm={() => handleRemoveProduct(remove, field)}
                      okText='确认'
                      cancelText='取消'
                    >
                      <DeleteOutlined twoToneColor='#ff0000' style={{ color: 'red' }} />
                    </Popconfirm>
                  }
                >
                  <div className='card_item'>
                    <div className='card_item_left'>
                      <FormUploadOneImg name={[field.name, 'img_url']} colon={false} aspect={typeObj[type].aspect} />
                    </div>
                    <div className='card_item_right'>
                      <Form.Item
                        rules={[{ required: true, message: '请选择链接' }]}
                        label='链接:'
                        name={[field.name, 'linkArr']}
                      >
                        <LinkFormat />
                      </Form.Item>
                      {type === 'navigationArr' && (
                        <Form.Item
                          rules={[{ required: true, message: '请输入文字内容' }]}
                          label='文字内容'
                          name={[field.name, 'content']}
                        >
                          <Input allowClear placeholder='请输入' maxLength={4} />
                        </Form.Item>
                      )}
                    </div>
                  </div>
                </Card>
              ))}

              <Button type='dashed' onClick={() => handleAddProduct(add)}>
                <PlusOutlined />
                添加({currentCount.length}/10)
              </Button>
            </div>
          )}
        </Form.List>

        {/* <Form.Item noStyle shouldUpdate>
          {() => (
            <Typography>
              <pre>{JSON.stringify(basisForm.getFieldsValue(), null, 2)}</pre>
            </Typography>
          )}
        </Form.Item> */}
      </Form>
    </div>
  )
}

export default forwardRef(LinkProduct)
